package com.dream.service.recommender.web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.result.AppResultBuilder;
import com.dream.service.recommender.web.manager.ClientManager;
import com.dream.service.recommender.web.model.Param;
import com.dream.service.recommender.web.processor.RequestProcessor;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 开放服务
 * Created by zhiji on 2016/3/24.
 */
public class OpenServlet extends HttpServlet {

    RequestProcessor requestProcessor;

    public RequestProcessor getRequestProcessor() {
        return requestProcessor;
    }

    public void setRequestProcessor(RequestProcessor requestProcessor) {
        this.requestProcessor = requestProcessor;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        requestProcessor = ClientManager.getClient("openRequestProcessor");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding(Param.default_encode);
        resp.setCharacterEncoding(Param.default_encode);
        resp.setContentType("text/html;charset=utf-8");
        JSONObject result;
        if(requestProcessor!=null){
            result = requestProcessor.processor(req);
        }else{
            result= new JSONObject();
            AppResultBuilder.buildProcessErrorResult(result, "");
        }
        resp.getOutputStream().write(result.toJSONString().getBytes(Charset.forName(Param.default_encode)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
